﻿using Bigger.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Bigger.Study.ConsoleApp.Async
{
    public class TAPAsyncExample : IExample
    {
        public void Execute()
        {

            CancellationTokenSource objCancellationTokenSource = new CancellationTokenSource();
            Task objTask = Task.Factory.StartNew(() =>
            {
                while (!objCancellationTokenSource.IsCancellationRequested)
                {
                    Console.WriteLine(RandomHelper.GetRandomInt(0, 100));
                }
            }, objCancellationTokenSource.Token);

            Thread.Sleep(5000);
            objCancellationTokenSource.Cancel();
            objCancellationTokenSource.Dispose();

            //不能在取消和回收以后马上new CancellationTokenSource，否则仍然会继续运行
            Thread.Sleep(500);

            ConsoleHelper.WriteLineYellow("==已取消运行==");
            ConsoleHelper.WriteLineYellow("==5秒后重新运行==");
            Thread.Sleep(5000);

            objCancellationTokenSource = new CancellationTokenSource();
            objTask = Task.Factory.StartNew(() =>
            {
                ConsoleHelper.WriteLineYellow("==5秒后正在运行==");
                while (!objCancellationTokenSource.IsCancellationRequested)
                {
                    Console.WriteLine(RandomHelper.GetRandomInt(0, 100));
                }
            }, objCancellationTokenSource.Token);

            Thread.Sleep(5000);
            objCancellationTokenSource.Cancel();
            objCancellationTokenSource.Dispose();
            Thread.Sleep(500);

            ConsoleHelper.WriteLineYellow("==已取消运行==");

            //不能在取消和回收以后马上new CancellationTokenSource，否则仍然会继续运行
            //Task.ContinueWith抛异常，并不会使Task.IsFaulted为true

            objCancellationTokenSource = new CancellationTokenSource();
            objTask = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    ConsoleHelper.WriteLineYellow("==休息5秒抛异常==");
                    Thread.Sleep(5000);
                    ConsoleHelper.WriteLineYellow("==5秒后抛异常==");
                    string.Format("{0}");
                    string.Concat("", "", "");
                }
            }, objCancellationTokenSource.Token);

            while (true)
            {
                if (objTask.IsFaulted)
                {
                    ConsoleHelper.WriteLineYellow("==由于抛异常而停止运行，CancellationTokenSource的状态：" + objCancellationTokenSource.IsCancellationRequested + "==");
                    break;
                }
            }
        }
    }
}
